package com.gooluke.auth.service;

import com.gooluke.auth.util.JwtUtils;
import com.gooluke.redis.uitl.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Resource
    private JwtUtils jwtUtils;
    @Autowired
    private RedisUtil redisUtil;

    public String refreshToken(String refreshToken) {
        if (!jwtUtils.validateToken(refreshToken)) {
            // 刷新令牌失效，直接返回401
            // todo 返回401
            return null;
        }
        String username = jwtUtils.getUsernameFromToken(refreshToken);
        // 生成新的访问令牌
        String token = jwtUtils.generateToken(username, jwtUtils.getRolesFromToken(refreshToken));
        redisUtil.setString("jwt:loginList:" + username, token, 15 * 60);
        return token;
    }

    public void invalidateToken(String token) {
        // 从Redis中删除登录名单
        redisUtil.del("jwt:loginList:" + jwtUtils.getUsernameFromToken(token));
    }
}